package xyz.lxbq.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import xyz.lxbq.pojo.Depart;
import xyz.lxbq.pojo.Emp;
import xyz.lxbq.pojo.EmpStatistics;
import xyz.lxbq.pojo.Loginlog;
import xyz.lxbq.service.EmpService;
import xyz.lxbq.service.LoginlogService;
import xyz.lxbq.utils.PageUtils;
import xyz.lxbq.utils.ResultMessage;
import xyz.lxbq.utils.Tongji;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author XuHu
 * @version 1.0
 * @date 2020/10/14 11:31
 */
@Controller
public class EmpController {

    @Autowired
    EmpService empService;
    @Autowired
    LoginlogService loginlogService;

    @RequestMapping("/emp_login")
    @ResponseBody  //将返回值转为JSON
    public ResultMessage login(Emp emp, HttpServletResponse response, HttpSession session,String ip ,String city) throws Exception{
        ResultMessage message = null;
        response.setContentType("text/html;charset=utf-8");
        Emp loginEmp = empService.login(emp);
        System.out.println(loginEmp);
        int aLlEmpCount = empService.getALlEmoCount();//获取总行数
        if(loginEmp != null){
            if (loginEmp.getFlag() == 1){
                //存session
                session.setAttribute("loginEmp",loginEmp);
                session.setAttribute("aLlEmpCount",aLlEmpCount);
                //存储登录日记
                Loginlog loginlog = new Loginlog(ip, emp.getNo(), city);
                loginlogService.addLoginLog(loginlog);

                message = new ResultMessage(400,"登录成功");

            }else{
                message = new ResultMessage(300,"账号已被禁用，请联系管理员!");
                //response.getWriter().write("<script>alert('账号已被禁用，请联系管理员!');location.href='login.jsp'</script>");
            }
        }else{
            message = new ResultMessage(100,"账号或密码错误!");
            // response.getWriter().write("<script>alert('账号或密码错误!');location.href='login.jsp'</script>");
        }
        //把message对象使用攻击，转换为json字符串，不用人工拼接
        return message;
    }

    @ResponseBody  //返回值转json
    @RequestMapping("/getLoginlog")
    public List<Loginlog> getLoginlog(HttpSession session){
        return loginlogService.getlastloginlog( ((Emp) session.getAttribute("loginEmp")).getNo());
    }
    /**
     * 新增员工
     */
    @RequestMapping("/addEmp")
    @ResponseBody  //将返回值转为JSON
    public ResultMessage addEmp(Emp emp){
        ResultMessage message = null;
        //判断输入的账户是否已经存在
        int i = empService.addEmp(emp);
        if(i>0){
               message = new ResultMessage(200,"员工添加成功");
        }else {
            message = new ResultMessage(300,"员工添加失败");
        }
        return message;
    }

    @RequestMapping("/empPageList/{pageIndex}/{pageSize}")
    String empPageList(@PathVariable("pageIndex") int pageIndex, @PathVariable("pageSize") int pageSize, Model model){
        int aLlEmpCount = empService.getALlEmoCount();//获取总行数
        List<Emp> empPage = empService.getEmpPage((pageIndex - 1) * pageSize, pageSize);//获取每页数据
        //封装工具类
        PageUtils pageUtils = new PageUtils(pageIndex,pageSize,aLlEmpCount,empPage);
        model.addAttribute("pageUtils",pageUtils);
        return "emplist";
    }

    //删除员工
    @RequestMapping("/deletedemp")
    @ResponseBody
    public ResultMessage deletedDepare( HttpServletResponse response,int id){
        ResultMessage message = null;
        response.setContentType("text/html;charset=utf-8");
        //存储新增部门
        int i = empService.deleteEmp(id);
        if (i == 1 ){
            message = new ResultMessage(200,"删除成功");
        }else{
            message = new ResultMessage(300,"删除失败");
        }
        return message;
    }

    /**
     * 获取每个部门有多少人 前端echars显示
     */
    @RequestMapping("/empStatistics_Echars")
    @ResponseBody
    public String  empStatisticsEchars ( HttpServletResponse response){
        response.setContentType("text/html;charset=utf-8");
        //执行
        List<Tongji> empStatistics = empService.getEmpStatistics();
        String JSONString = JSONObject.toJSONString(empStatistics);
        return JSONString;
    };
    /**
     * 修改密码
     */
    @ResponseBody
    @RequestMapping("/updatePassword")
    public ResultMessage updatePassword(HttpServletResponse response,String pass,int id){
        ResultMessage message = null;
        response.setContentType("text/html;charset=utf-8");
        int count = empService.updataPassword(pass, id);
        if(count == 1){
            message = new ResultMessage(200,"修改成功");
        }else{
            message = new ResultMessage(300,"修改失败");
        }
        return message;
    }


    /**
     * 更改头像
     */
    @RequestMapping("/changephoto")
    @ResponseBody
    public void changePhoto(MultipartFile mFile, HttpSession session,HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        String originalFilename = mFile.getOriginalFilename();
        String[] split = originalFilename.split("\\.");
        String s = UUID.randomUUID().toString() + "." + split[split.length - 1];
        System.out.println("新名字："+s);
        String realPaths = session.getServletContext().getRealPath("/media/upload");
        realPaths=realPaths+"\\"+s;
        mFile.transferTo(new File(realPaths));
        System.out.println("上传到的服务器地址："+realPaths);
        System.out.println("文件上传成功~~~~");
        //session中存储的登录信息没有更新

        Emp empLogin = (Emp) session.getAttribute("loginEmp");
        Emp emp = new Emp();
        emp.setName(empLogin.getName());
        emp.setId(empLogin.getId());
        emp.setPhoto(s);
        empService.updatePhoto(emp);

        session.setAttribute("loginEmp",emp);
        response.getWriter().write("<script>alert('头像更换成功');parent.location.href='/index';</script>");

    }

}
